import {
  _decorator,
  Component,
  Node,
  Sprite,
  UITransform,
  Animation,
  AnimationClip,
  animation,
  Vec3,
  SpriteFrame,
  debug,
} from 'cc'
import { TILE_HEIGHT, TILE_WIDTH } from '../Scripts/Tile/TileManage'
import ResourceManage from '../Runtime/resourceManage'
import {
  CONTROLLER_ENUM,
  DIRECTION_ENUM,
  DIRECTION_ORDER_ENUM,
  ENTITY_STATE_ENUM,
  ENTITY_TYPE_ENUM,
  EVENT_ENUM,
  PARAMS_NAME_ENUM,
  SPIKES_TYPE_MAP_TOTALCOUNT_ENUN,
} from '../Enums'
import EventManage from '../Runtime/eventManage'
import { IEntity, ISpikes } from '../Levels'
import { PlayerStateMachine } from '../Player/PlayerStateMachine'
import { randomByLen } from '../Utils'
import { SpikesStateMachine } from './SpikesStateMachine'
import DataManage from '../Runtime/dataManage'
const { ccclass, property } = _decorator

@ccclass('SpikesManage')
export class SpikesManage extends Component {
  id: string = randomByLen(12)
  x: number = 0
  y: number = 0
  fsm: SpikesStateMachine

  private _count: number
  private _totalCount: number

  private type: ENTITY_TYPE_ENUM

  get count() {
    return this._count
  }

  set count(newCount: number) {
    this._count = newCount
    this.fsm.setParams(PARAMS_NAME_ENUM.SPIKES_CUR_COUNT, newCount)
  }

  get totalCount() {
    return this._totalCount
  }

  set totalCount(newCount: number) {
    this._totalCount = newCount
    this.fsm.setParams(PARAMS_NAME_ENUM.SPIKES_TOTAL_COUNT, newCount)
  }

  async init(params: ISpikes) {
    const sprite = this.addComponent(Sprite)
    sprite.sizeMode = Sprite.SizeMode.CUSTOM

    const transform = this.getComponent(UITransform)
    transform.setContentSize(TILE_WIDTH * 4, TILE_HEIGHT * 4)

    this.fsm = this.addComponent(SpikesStateMachine)
    await this.fsm.init()

    this.x = params.x
    this.y = params.y
    this.type = params.type
    // 设置初始方向
    this.totalCount = SPIKES_TYPE_MAP_TOTALCOUNT_ENUN[this.type]
    // 通过设置参数来执行初始动画
    this.count = params.count

    // 监听玩家移动，改变敌人朝向
    EventManage.Instance.on(EVENT_ENUM.PLAYER_MOVE_END, this.onLoop, this)
  }
  onDestroy() {
    super.onDestroy()
    EventManage.Instance.off(EVENT_ENUM.PLAYER_MOVE_END, this.onLoop)
  }

  protected update(dt: number): void {
    this.node.setPosition(this.x * TILE_WIDTH - 1.5 * TILE_WIDTH, -this.y * TILE_HEIGHT + 1.5 * TILE_HEIGHT)
  }

  onLoop() {
    if (this.count === this.totalCount) {
      this.count = 1
    } else {
      this.count++
    }
    this.onAttack()
  }
  backZero() {
    this.count = 0
  }
  onAttack() {
    if (!DataManage.Instance.player) return
    let { x: playerX, y: playerY } = DataManage.Instance.player
    if (this.x == playerX && this.y == playerY && this.count == this.totalCount) {
      EventManage.Instance.emit(EVENT_ENUM.ATTACK_PLAYER, ENTITY_STATE_ENUM.DEATH)
    }
  }
}
